<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <div class="card-header">
        <h2>个人中心</h2>
      </div>

      <div class="avatar-section">
        <div class="avatar-wrapper">
          <el-avatar :size="120" :src="userInfo.avatar || defaultAvatar" />
          <div class="avatar-overlay">
            <el-upload
              class="avatar-uploader"
              action=""
              :http-request="uploadAvatar"
              :show-file-list="false"
              accept="image/*"
            >
              <el-icon class="upload-icon"><Camera /></el-icon>
            </el-upload>
          </div>
        </div>
        <div class="user-welcome">
          <h3 class="welcome-text">
            欢迎回来，{{ userInfo.nickname || userInfo.username }}
          </h3>
          <div class="user-status">
            <el-tag
              :type="statusRoleMap[userInfo.role]?.type || 'info'"
              effect="light"
              size="small"
            >
              {{ statusRoleMap[userInfo.role]?.text || "未知角色" }}
            </el-tag>
          </div>
        </div>
      </div>

      <el-divider content-position="center">
        <el-icon><Star /></el-icon>
      </el-divider>

      <el-form
        label-position="top"
        class="profile-form"
        :rules="userCenterFormRules"
        :model="userInfo"
        ref="userCenterFormRef"
      >
        <div class="form-grid">
          <el-form-item label="用户名">
            <el-input v-model="userInfo.username" disabled>
              <template #prefix>
                <el-icon><User /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="userInfo.nickname" placeholder="请输入昵称">
              <template #prefix>
                <el-icon><ChatDotRound /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="邮箱" prop="email">
            <el-input v-model="userInfo.email" placeholder="请输入邮箱">
              <template #prefix>
                <el-icon><Message /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="电话" prop="mobile">
            <el-input v-model="userInfo.mobile" placeholder="请输入电话号码">
              <template #prefix>
                <el-icon><Phone /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <!-- <el-form-item label="密码" prop="password">
            <el-input v-model="userInfo.password" placeholder="请输入密码">
            </el-input>
          </el-form-item>

          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input
              type="password"
              v-model="userInfo.confirmPassword"
              placeholder="请再次输入密码"
              show-password
            />
          </el-form-item> -->
        </div>

        <el-form-item label="性别">
          <el-radio-group v-model="userInfo.gender" class="custom-radio-group">
            <el-radio value="M">男</el-radio>
            <el-radio value="F">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item class="action-buttons">
          <el-button
            type="primary"
            @click="confirmSave"
            :loading="loading.save"
            class="save-button"
          >
            <el-icon><Check /></el-icon>保存修改
          </el-button>
          <el-button @click="confirmLogout" class="logout-button" type="danger">
            <el-icon><SwitchButton /></el-icon>退出登录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { onMounted, ref, reactive } from "vue";
import { userGetById, userEdit, userLogout } from "@/apis/user/user";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { upload } from "@/apis/upload";
import {
  Check,
  Camera,
  User,
  ChatDotRound,
  Message,
  Phone,
  SwitchButton,
  Star,
} from "@element-plus/icons-vue";

const router = useRouter();
const userInfo = ref({});
const defaultAvatar = ref("/src/assets/default-avatar.png");
const loading = ref({
  save: false,
  upload: false,
});

onMounted(async () => {
  try {
    const res = await userGetById();
    userInfo.value = res.data;
  } catch (error) {
    ElMessage.error("获取用户信息失败");
    console.error(error);
  }
});

const confirmSave = () => {
  ElMessageBox.confirm("确定要保存修改的个人信息吗？", "确认操作", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "info",
  })
    .then(() => {
      onSave();
    })
    .catch(() => {
      ElMessage.info("已取消保存");
    });
};

const onSave = async () => {
  try {
    loading.value.save = true;
    await userEdit(userInfo.value);
    ElMessage.success({
      message: "个人信息保存成功",
      type: "success",
      duration: 2000,
    });
  } catch (error) {
    ElMessage.error("保存失败，请稍后重试");
    console.error(error);
  } finally {
    loading.value.save = false;
  }
};

const confirmLogout = () => {
  ElMessageBox.confirm("确定要退出登录吗？", "退出提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      logout();
    })
    .catch(() => {
      ElMessage.info("已取消退出");
    });
};

const logout = () => {
  router.push("/");
  // 清空缓存
  sessionStorage.clear;
  ElMessage.success("已成功退出登录");
};

const uploadAvatar = async (options) => {
  try {
    loading.value.upload = true;
    const formData = new FormData();
    formData.append("file", options.file);

    const res = await upload(formData);

    userInfo.value.avatar = res.data;

    ElMessage.success({
      message: "头像上传成功",
      type: "success",
      duration: 2000,
    });
  } catch (error) {
    ElMessage.error("头像上传失败");
    console.error(error);
  } finally {
    loading.value.upload = false;
  }
};

// 角色类型
const statusRoleMap = {
  1: { text: "普通用户", type: "info" },
  2: { text: "管理员", type: "primary" },
};

const userCenterFormRef = ref();

// 密码校验函数
const validatePass = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请输入密码"));
  } else {
    if (value.length < 6) {
      callback(new Error("密码长度至少6位"));
    }
    if (!/[A-Z]/.test(value)) {
      callback(new Error("密码需包含大写字母"));
    }
    if (!/[0-9]/.test(value)) {
      callback(new Error("密码需包含数字"));
    }
    if (userInfo.confirmPassword !== "") {
      userCenterFormRef.value.validateField("confirmPassword");
    }
    callback();
  }
};

// 确认密码校验
const validateConfirmPass = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请再次输入密码"));
  } else if (value !== userInfo.password) {
    callback(new Error("两次输入密码不一致"));
  } else {
    callback();
  }
};

// 表单校验规则
const userCenterFormRules = reactive({
  username: [
    { required: true, message: "用户名不能为空", trigger: "blur" },
    { min: 3, max: 25, message: "用户名长度为3~25", trigger: "blur" },
  ],
  password: [{ required: true, validator: validatePass, trigger: "blur" }],
  confirmPassword: [
    { required: true, validator: validateConfirmPass, trigger: "blur" },
  ],
  email: [
    { required: true, message: "邮箱不能为空", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱格式", trigger: "blur" },
  ],
  mobile: [
    { required: true, message: "手机号不能为空", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  captcha: [
    { required: true, message: "验证码不能为空", trigger: "blur" },
    { min: 4, max: 6, message: "请输入正确的验证码", trigger: "blur" },
  ],
});
</script>

<style scoped>
.profile-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 32px;
  min-height: calc(100vh - 64px);
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e8f0 100%);
}

.profile-card {
  width: 100%;
  max-width: 680px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  border-radius: 16px;
  transition: all 0.4s ease;
  overflow: hidden;
  border: none;
}

.profile-card:hover {
  transform: translateY(-8px);
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.15);
}

.card-header {
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 20px;
  margin-bottom: 30px;
}

.card-header h2 {
  margin: 0;
  color: #303133;
  font-weight: 700;
  font-size: 26px;
  letter-spacing: 1px;
  position: relative;
  padding-left: 16px;
  display: inline-block;
}

.card-header h2::before {
  content: "";
  position: absolute;
  left: 0;
  top: 5%;
  height: 90%;
  width: 5px;
  background: linear-gradient(to bottom, #409eff, #67c23a);
  border-radius: 6px;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 30px;
  position: relative;
}

.avatar-wrapper {
  position: relative;
  border-radius: 50%;
  overflow: hidden;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
  border: 5px solid #fff;
  transition: all 0.3s ease;
  z-index: 2;
}

.avatar-wrapper:hover .avatar-overlay {
  opacity: 1;
}

.avatar-wrapper:hover {
  box-shadow: 0 8px 25px rgba(64, 158, 255, 0.5);
  transform: scale(1.05);
}

.el-avatar {
  background-color: #f0f2f5;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  opacity: 0;
  transition: opacity 0.3s ease;
  cursor: pointer;
  border-radius: 50%;
}

.upload-icon {
  color: white;
  font-size: 32px;
  filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.3));
}

.user-welcome {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 16px;
}

.welcome-text {
  margin: 16px 0 8px;
  color: #303133;
  font-weight: 600;
  font-size: 20px;
}

.user-status {
  margin-bottom: 10px;
}

.el-divider {
  margin: 24px 0;
}

.el-divider :deep(.el-divider__text) {
  background-color: transparent;
  color: #909399;
  padding: 0 20px;
}

.profile-form {
  padding: 0 8px;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
}

.profile-form :deep(.el-form-item__label) {
  font-weight: 600;
  color: #606266;
  font-size: 14px;
  margin-bottom: 4px;
}

.profile-form :deep(.el-input__wrapper) {
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  padding: 4px 11px;
}

.profile-form :deep(.el-input__wrapper:hover) {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.profile-form :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
}

.profile-form :deep(.el-input__prefix) {
  margin-right: 8px;
  color: #909399;
}

.profile-form :deep(.el-input.is-disabled .el-input__wrapper) {
  background-color: #f5f7fa;
}

.custom-radio-group {
  display: flex;
  gap: 20px;
}

.custom-radio-group :deep(.el-radio__inner) {
  width: 20px;
  height: 20px;
  transition: all 0.3s ease;
}

.custom-radio-group :deep(.el-radio__input.is-checked .el-radio__inner) {
  background-color: #409eff;
  border-color: #409eff;
  box-shadow: 0 0 10px rgba(64, 158, 255, 0.4);
}

.custom-radio-group :deep(.el-radio__label) {
  font-size: 15px;
  padding-left: 8px;
}

.action-buttons {
  margin-top: 40px !important;
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-left: 180px;
}

.save-button,
.logout-button {
  padding: 12px 30px;
  font-weight: 600;
  border-radius: 10px;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 15px;
}

.save-button {
  background: linear-gradient(45deg, #409eff, #53a8ff);
  border: none;
}

.save-button:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 15px rgba(64, 158, 255, 0.4);
}

.logout-button {
  background: #fff;
  color: #f56c6c;
  border: 1px solid #f56c6c;
}

.logout-button:hover {
  color: #fff;
  background: linear-gradient(45deg, #f56c6c, #fc8e8e);
  border-color: transparent;
  transform: translateY(-3px);
  box-shadow: 0 8px 15px rgba(245, 108, 108, 0.3);
}

/* 响应式调整 */
@media (max-width: 768px) {
  .profile-container {
    padding: 16px;
  }

  .profile-card {
    padding: 16px;
  }

  .card-header h2 {
    font-size: 22px;
  }

  .form-grid {
    grid-template-columns: 1fr;
    gap: 12px;
  }

  .action-buttons {
    flex-direction: column;
  }

  .save-button,
  .logout-button {
    width: 100%;
    padding: 10px;
  }

  .welcome-text {
    font-size: 18px;
  }
}
</style>
